import { defineStore } from 'pinia'
import { useAuthStore } from "@/store/userInfo"

export const useUser = defineStore("user", {
    state: () => ({
        //账号昵称
        nickname: '',
        //好友信息
        friendsInfo: {} as any,
        //好友列表 + 好友消息
        friendsListInfo: [] as any,
        // WebSocket实例
        webSocketInstance: null as any
    }),
    // Getters 相当于组件中的计算属性
    getters: {},
    actions: {
        //创建websocket实例连接
        async createWebSocket(nickname: string) {
            //验证是否已有存在的实例，如果存在则先关闭
            if (this.webSocketInstance) {
                this.webSocketInstance.close();
            }
            return new Promise((resolve, reject) => {
                console.log(nickname)
                if (nickname == '') {
                    reject('空账号')
                    return
                }
                //设置用户昵称
                this.nickname = nickname
                //建立websocket全双工通信连接
                this.webSocketInstance = new WebSocket('ws://127.0.0.1:8091/websocket/' + nickname);

                //监听websocket打开事件
                this.webSocketInstance.onopen = () => {
                    console.log('websocket is connected');
                    resolve(true)
                }
                //监听websocket消息事件
                this.webSocketInstance.onmessage = (event: any) => {
                    //接收消息转JSON对象
                    const data = JSON.parse(event.data)
                    console.log("data = ", data) //打印消息
                    if (data.type === 'updateFriendsList') {
                        this.updateFriends(data)
                        console.log('进入了updateFriendList')
                    }
                    else if (data.type === 'messages') {
                        console.log('进入了messages')
                        console.log('监听到data', data)
                        let findIndex = this.friendsListInfo.findIndex((object: any) => object.nickname === data.sendNickname)
                        if (findIndex !== -1) {
                            console.log('准备更新接收的消息', data.messages)
                            if (this.friendsListInfo[findIndex].nickname === this.friendsInfo.nickname) {
                                this.friendsInfo.latestNews = data.messages
                                this.friendsInfo.messages.push({
                                    type: 'friend',
                                    message: data.messages,
                                    avatarUrl: data.avatar
                                })
                            } else {
                                this.friendsListInfo[findIndex].latestNews = data.messages
                                this.friendsListInfo[findIndex].messages.push({
                                    type: 'friend',
                                    message: data.messages,
                                    avatarUrl: data.avatar
                                })
                                 // 如果不是当前查看的好友，增加未读消息计数
                                this.friendsListInfo[findIndex].unreadMessagesCount += 1;
                                
                            }
                        }
                    }
                }

                //监听websocket关闭事件
                this.webSocketInstance.onclose = () => {
                    console.log('websocket is disconnected');
                    resolve(false);
                }
                //监听websocket异常事件
                this.webSocketInstance.onerror = (error: any) => {
                    console.error('websocket error', error);
                    reject(error);
                }

            })
        },

        async updateFriends(data: any) {
            //验证是否存在好友

            //迭代更新好友列表信息

            for (let i = 0; i < data.messages.length; i++) {
                let findIndex = this.friendsListInfo.findIndex((object: any) => object.nickname === data.messages[i].nickname);
                // 验证是否一致
                // 不一致，新增好友
                if (findIndex === -1) {
                    console.log("准备新增好友")
                    let friend = {
                        status: true, // 是否在线状态
                        nickname: data.messages[i].nickname, // 好友账号昵称
                        latestNews: '好友上线了，可以开始聊天了', // 最新消息
                        avatar: data.messages[i].avatar,
                        unreadMessagesCount:1, // 未读消息数量
                        // 消息集合
                        messages: [
                            {
                                type: 'friend', // 消息类型
                                message: '好友上线了！', // 消息内容
                                avatar: data.messages[i].avatar,
                            }
                        ]

                    }
                    this.friendsListInfo.push(friend)
                }
            }

            //迭代已经存储的好友列表
            for (let i = 0; i < this.friendsListInfo.length; i++) {
                //查找好友
                //移除或者修改在线状态
                let findIndex1 = data.messages.findIndex((object: any) => object.nickname === this.friendsListInfo[i].nickname);
                if (findIndex1 == -1) {
                    //不存在代表已经离线
                    this.friendsListInfo[i].status = false;
                    //验证是否为当前选择好友信息
                    if (this.friendsInfo.nickname === this.friendsListInfo[i].nickname) {
                        // 更新当前选择好友的在线状态，更新离线
                        this.friendsInfo.status = false;
                    }
                }
                else {
                    // 存在代表已经上线
                    this.friendsListInfo[i].status = true
                    //验证是否为当前选择好友信息
                    if (this.friendsInfo.nickname === data.messages[findIndex1].nickname) {
                        // 更新当前好友的在线状态，更新在线
                        this.friendsInfo.status = true
                    }
                }

            }
        },
        async sendMessages(receiveMessage: string) {
            console.log("发送的消息是:", receiveMessage)
            if (!this.friendsInfo.nickname) {
                return false;
            }
            // 获取authStore实例
            const authStore = useAuthStore();
            // 从authStore获取avatarUrl
            const avatarUrl = authStore.avatarUrl;
            let message = {
                type: "messages",
                sendNickname: this.nickname,
                receiveNickname: this.friendsInfo.nickname,
                messages: receiveMessage,
                avatar: ''
            }
            this.webSocketInstance.send(JSON.stringify(message));
            let addMessage = {
                type: 'my',
                message: receiveMessage,
                avatar: avatarUrl // 使用获取的avatarUrl
            }
            this.friendsInfo.messages.push(addMessage);
            this.friendsInfo.latestNews = receiveMessage
            return true;
        }
    },
    persist:{
        storage: sessionStorage,
    }
})